package com.kuang.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/1.png");
        System.out.println("下载文件的路径是："+realPath);

        String fileName = realPath.substring(realPath.lastIndexOf("//") + 1);

        //让浏览器支持下载的东西
        resp.setHeader("Content-Disposition","attachment;filename:"+fileName);

        FileInputStream in = new FileInputStream(realPath);

        //创建缓冲区
        int len=0;
        byte[] buffer = new byte[1024];

        ServletOutputStream out = resp.getOutputStream();

        while ((len= in.read(buffer)) >0){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
